package helpers;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;


public class LastSearchHelper {
	private static int limit = 30;
	
	private static ArrayList<String> lastSearch = new ArrayList<String>();
	
	private static String cachename = "lastSearch";

	public static int getLimit() {
		return limit;
	}

	public static void setLimit(int limit) {
		LastSearchHelper.limit = limit;
	}

	public static ArrayList<String> getLastSearch() {
		Cache cache = init();
		if (cache.containsKey(cachename)) {
			lastSearch = (ArrayList<String>) cache.get(cachename);
		} else {
			cache.put(cachename, lastSearch);
		}
		return lastSearch;
	}

	public static void setSearch(String name) {
		Cache cache = init();
		name = name.replace("+", " ");
		lastSearch = getLastSearch();
		
		if (!lastSearch.contains(name)) {
			if (lastSearch.size() < LastSearchHelper.limit) {
				lastSearch.add(name);
			} else {
				lastSearch.remove(0);
				lastSearch.add(name);
			}
		}
		
		cache.put(cachename, lastSearch);
	}
	
	private static Cache init() {
		//Set cache
        Cache cache=null;
        try {
            cache = javax.cache.CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           e.printStackTrace();
        }
        return cache;
	}
}
